<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.9
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ################

class JFX_Module_Jfxjs extends JFX_Module {

    public $keyname = 'jfxjs';
    public $title = 'JFX JS';
    public $version = '0.0.1';
    public $dependencies = array(

    );
    public $browserVersions = array('lt IE 6', 'IE 6', 'lt IE 7', 'IE 7', 'lt IE 8', 'IE 8');

    public function __construct(){
        parent::__construct();
		$this->title = $this->lang('module_title');

    }


	public function getFile($id){
		$CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
		if(file_exists($this->dirname.'/files/'.$id.'.css')){
			return file_get_contents($this->dirname.'/files/'.$id.'.css');
		}else{
			return '';
		}
	}


	public function showJsLinksForPage($pageid){
		$CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
		$VIEW = JFX::registry('JFX_View');

		$js = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}jfxjs_pages_to_javascripts WHERE page_id = '{$pageid}' ORDER BY sorting ASC");
		foreach($js as $k=>$v){
			$jsData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}jfxjs_javascripts WHERE id = '{$v['js_key']}'");

			switch($jsData['browser_version']){
				case 'lt IE 6':
				case 'IE 6':
				case 'lt IE 7':
				case 'IE 7':
				case 'lt IE 8':
				case 'IE 8':
					$VIEW->addIeJsLink($CONFIG->baseUrl.$CONFIG->moduleJsFolder.'/'.$this->keyname.'/'.$v['js_key'].'.js', $jsData['browser_version']);
				break;
				default:
					$this->addJsLink($v['js_key'].'.js');
			}

		}

	}



	public function setFile($id, $code='', $browserVersion=''){
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');

		$dbParams = array(
			'id' => $id,
			'browser_version' => $browserVersion
		);

		$id = $DB->escape($id);
		if($DB->countRows($CONFIG->dbprefix.'jfxjs_javascripts', "id = '{$id}'")>0){
			// update
			$DB->update($CONFIG->dbprefix.'jfxjs_javascripts', $dbParams, "id = '{$id}'");
		}else{
			// insert
			$DB->insert($CONFIG->dbprefix.'jfxjs_javascripts', $dbParams);
		}

		$fh = fopen($this->dirname.'/files/'.$id.'.js', 'w');
		fwrite($fh, $code);
		fclose($fh);
	}


    public function getToolbarButtons($pageid){
        $buttons = array();
        $button = array(
            'id' => 'JFXJSButton',
            'image' => 'cog.png',
            'title' => $this->lang('manage_javascript_associations'),
            'alt' => $this->lang('js'),
            'click' => '
                var href = "'.$this->adminUrl.'/manage-javascript-associations/";
                tb_show("'.$this->lang('manage_javascript_associations').'", href, false);
                $(\'#TB_window\').unload(function(){
                    window.location = window.location;
                });'
        );
        $buttons[] = $button;
        return $buttons;
    }

    public function serve(){
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $USER = JFX::registry('JFX_User');
        $CRYPT = JFX::registry('JFX_Crypt');
        $LINK = JFX::registry('JFX_Link');
        $THEME = JFX::registry('JFX_Theme');
        $CORE = JFX::registry('JFX_Core');
        $SETTINGS = JFX::registry('JFX_Settings');

        $req = explode('?', THIS_PAGE_URL);
        $requestedFile = str_replace($this->publicUrl, '', $req[0]);
        $requestedFile = str_replace('../', '/', $requestedFile);
        if(file_exists($this->dirname.'/public/'.$requestedFile.'.php')){
            $SMARTY->assign('publicUrl', $this->publicUrl);
            include($this->dirname.'/public/'.$requestedFile.'.php');
        }
        else{
            $LINK->throw404();
            exit;
        }
    }


    public function printJsFile($filename){
        $DB = JFX::registry('db');
        $CONFIG = JFX::registry('config');
        $fileParts = explode('.', $filename);
        $jsKey = preg_replace('/[^a-zA-Z0-9]/', '', $fileParts[0]);
        if($DB->countRows($CONFIG->dbprefix.'jfxjs_javascripts', "id = '{$jsKey}'")>0){
            while(ob_get_level()>0) ob_end_clean();

            $searches = array(
                ':|imgUrl|:',
                ':|imageUrl|:',
                ':|cssUrl|:',
                ':|jsUrl|:',
                ':|moduleUrl|:'
            );
            $replacements = array(
                $CONFIG->baseUrl.$CONFIG->moduleImageFolder,
                $CONFIG->baseUrl.$CONFIG->moduleImageFolder,
                $CONFIG->baseUrl.$CONFIG->moduleCssFolder,
                $CONFIG->baseUrl.$CONFIG->moduleJsFolder,
                $CONFIG->baseUrl.$CONFIG->moduleServerFolder
            );

            $fData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}jfxjs_javascripts WHERE id = '{$jsKey}'");

            header('Content-type: text/javascript');
            $jsString = file_get_contents($this->dirname.'/files/'.$fData['id'].'.js');
            
            echo $jsString;
            exit;
        }else{
            return parent::printJsFile($filename);
        }
    }

    public function getBlockActions(){
        return array(
            
        );
    }


    public function editPageJs($PAGE){

        $_GET['page'] = $PAGE->details['id'];

        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $LANG = JFX::registry('lang');
        $THEME = JFX::registry('JFX_Theme');

        include($this->dirname.'/admin-actions/manage-javascript-associations.php');
    }


	public function getPageActionButtons($blockId, $pageid){
		$buttons = array();

        $button = new JFX_Page_Button;
        $button->imageUrl = $this->imageUrl.'/cog.png';
        $button->alternativeText = $this->lang('js');
        $button->title = $this->lang('js');
        $button->moduleName = $this->keyname;
        $button->moduleMethod = 'editPageJs';
		$button->pageId = $pageid;
		$button->id = $blockId;
		$button->blockId = $blockId;

        $buttons[] = $button;

        return $buttons;
	}



    public function getContent($params){
        return '';
    }

    public function prepare($details){
        return $this->getContent($details);
    }
    


    public function admin($url, $dirname){
        //$this->resetLanguages();
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $SMARTY->assign('actionUrl', $url);
        $LANG = JFX::registry('lang');
        $THEME = JFX::registry('JFX_Theme');

        $THEME->breadcrumbs[0]->set('icon', $this->imageUrl.'/cog.png');
        $THEME->addBreadcrumb($this->adminUrl, $this->getTitle());

        $this->addStylesheet('admin.css');

        $tabs = array(
            array(
                'keyname' => 'list',
                'title' => $this->lang('list'),
                'url' => $url.'/list',
                'class_name' => ''
            ),
            array(
                'keyname' => 'new',
                'title' => $this->lang('new'),
                'url' => $url.'/new-javascript/',
                'class_name' => ''
            ),
            array(
                'keyname' => 'sort',
                'title' => $this->lang('sort_default'),
                'url' => $url.'/sort-default-javascripts/',
                'class_name' => ''
            )
        );

        // find our selected tab
        $urlParts = explode('?', THIS_PAGE_URL);
        $urlParts = explode('/', $urlParts[0]);
        foreach($urlParts as $k=>$v){
            if($v == $this->keyname) break;
        }
        $selectedTab = (array_key_exists($k+1, $urlParts))
            ? $urlParts[$k+1]
            : ''
            ;

        if($selectedTab == ''){
            $selectedTab = 'list';
        }

        foreach($tabs as $k=>$tab){
            if($selectedTab == $tab['keyname']){
                $tabs[$k]['class_name'] .= ' jfxjs-selected';
            }
        }

        //include('admin-actions/tabs.php');

        $selectedTab = str_replace('../', '/', $selectedTab);


            if(file_exists($dirname.'/admin-actions/'.$selectedTab.'.php')) include('admin-actions/'.$selectedTab.'.php');
            else echo $selectedTab.'.php does not exists';


        
    }


    public function install(){
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)).'/install';
        include('install/install.php');
    }


    public function uninstall(){
        $VIEW = JFX::registry('JFX_View');
        $SMARTY = JFX::registry('Smarty');
        $USER = JFX::registry('JFX_User');
        $CONFIG = JFX::registry('config');
        $DB = JFX::registry('db');
        $dirname = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__FILE__)).'/install';
        include('install/uninstall.php');
    }




}